from flask import Blueprint, request, redirect, url_for
from common.libs.Helper import ops_renderJSON, iPagenation, ops_render
from common.models.book_index import BookIndex
from common.models.book_detail import BookDetail
from common.models.pickclass import Pickclass
from application import db, app
from common.libs.DataHelper import getCurrentTime
from common.models.record import Record
import flask_excel as excel
from qiniu import Auth
from qiniu import put_data
from qiniu import BucketManager
import os

book_page = Blueprint("book_page", __name__)


def pagesadmin(bookindex):
    req = request.values
    page = 1
    if 'p' in req and req['p']:
        page = int(req['p'])

    page_params = {
        'total_count': bookindex.count(),
        "page_size": 8,
        'page': page,
        'url': "/book/bookindex?",
    }
    pages = iPagenation(page_params)
    # -1 - 30,30 - 60 ,60 - 90
    offset = (page - 1) * page_params['page_size']
    limit = page * page_params['page_size']
    bookindex = bookindex[offset:limit]

    return pages, bookindex


def pagessearch(parterindex, url):
    req = request.values
    page = 1
    if 'p' in req and req['p']:
        page = int(req['p'])

    page_params = {
        'total_count': parterindex.count(),
        "page_size": 8,
        'page': page,
        'url': "/book/booksearch?" + url,
    }
    pages = iPagenation(page_params)
    # -1 - 30,30 - 60 ,60 - 90
    offset = (page - 1) * page_params['page_size']
    limit = page * page_params['page_size']
    parterindex = parterindex[offset:limit]

    return pages, parterindex


@book_page.route('/bookindex', methods=['GET', 'POST'])
def bookindex():
    bookindex = BookIndex.query.filter_by(mark=1).order_by(BookIndex.created_time.desc())
    pages, bookindex = pagesadmin(bookindex)
    bookclass = Pickclass.query.filter_by(type="信息存档").all()
    title = "招定标档案信息存档"
    return ops_render("/book/bookindex.html",
                      {"bookindex": bookindex, "pages": pages, "bookclass": bookclass, "title": title})


@book_page.route('/booksearch', methods=['GET', 'POST'])
def booksearch():
    a = request.args.to_dict()
    for key in list(a.keys()):
        if a.get(key) == "不限":
            del a[key]
    for key in list(a.keys()):
        if not a.get(key):
            del a[key]
    if "p" in a:
        del a["p"]

    type = request.args.get('type')
    # sn = request.args.get('sn')
    form = request.args.get('form')
    company = request.args.get('company')
    isover = request.args.get('isover')
    gcname = request.args.get('gcname')
    url = "type=" + type + "&form=" + form + "&company=" + company + "&isover=" + isover + "&gcname=" + gcname + "&mark=1"

    if gcname != "":
        bookindex = BookIndex.query.filter(BookIndex.gcname.like('%' + gcname + '%'))
        pages, bookindex = pagessearch(bookindex, url)
        bookclass = Pickclass.query.filter_by(type="信息存档").all()
        return ops_render("/book/bookindex.html", {"bookindex": bookindex, "pages": pages, "bookclass": bookclass})
    else:
        bookindex = BookIndex.query.filter_by(**a).order_by(BookIndex.created_time.desc())
        pages, bookindex = pagessearch(bookindex, url)
        bookclass = Pickclass.query.filter_by(type="信息存档").all()
        return ops_render("/book/bookindex.html", {"bookindex": bookindex, "pages": pages, "bookclass": bookclass})


# 搜索函数
def make_excel_list(data, column_names):
    list_data = []
    list_data.append(column_names)
    for item in data:
        tmp = [item.htsn, item.name, item.project, item.aname, item.bname, item.filename, item.filenum, item.num,
               item.dfnum, item.cwnum, item.cdnum, item.creater.nickname, item.creater.company, item.creater.department]
        list_data.append(tmp)
    return list_data


# excel.init_excel(app)


# @seal_page.route("/export", methods=['GET'])
# def export_records():
#     starttime = request.args.get('starttime')
#     endtime = request.args.get('endtime')
#
#     query_sets = SealOrder.query.filter(
#         SealOrder.created_time.between(starttime, endtime), SealOrder.type == "合同", SealOrder.mark == 2).order_by(
#         SealOrder.created_time.desc()).all()
#     column_names = ['合同编号', '合同名称', '项目', '甲方名称', '乙方名称', '附件名称', '合同页数', '总分数', '对方份数', '财务份数', '存档份数', '申请人', '申请公司',
#                     '申请部门']
#     excel_data = make_excel_list(query_sets, column_names)
#
#     # app.logger.info(excel_data)
#
#     return excel.make_response_from_array(excel_data, file_type='xls',
#                                           file_name="导出数据",
#                                           sheet_name='合同信息')


# 新增台账
@book_page.route('/addindex', methods=['GET', 'POST'])
def addindex():
    type = request.form.get("type")
    usercompany = request.form.get("usercompany")
    company = request.form.get("company")
    projectname = request.form.get("projectname")
    bname = request.form.get("bname")
    num = request.form.get("num")
    sn = request.form.get("sn")
    gcname = request.form.get("gcname")
    dbtime = request.form.get("dbtime")
    zjzb = request.form.get("zjzb")
    special = request.form.get("special")

    uid = request.form.get("uid")
    isover = "否"
    num2 = num.replace(",", "")
    num3 = num2.replace("%", "")
    num1 = float(num3)

    if company != None:
        usercompany = company

    if num1 >= 1000000:
        isover = "是"

    bookindex = BookIndex()
    bookindex.projectname = projectname
    bookindex.type = type
    bookindex.mark = 1
    bookindex.uid = uid
    bookindex.bname = bname
    bookindex.num = num
    bookindex.isover = isover
    bookindex.company = usercompany
    bookindex.sn = sn
    bookindex.gcname = gcname
    bookindex.dbtime = dbtime
    bookindex.zjzb = zjzb
    bookindex.special = special
    bookindex.created_time = bookindex.updated_time = getCurrentTime()
    db.session.add(bookindex)
    db.session.commit()

    return ops_renderJSON(msg="新建成功")


# 修改台账信息
@book_page.route('/updataindex', methods=['GET', 'POST'])
def updataindex():
    req = request.values
    id = req['id'] if "id" in req else ""
    type = req['type'] if "type" in req else ""
    usercompany = req['usercompany'] if "usercompany" in req else ""
    company = req['company'] if "company" in req else ""
    projectname = req['projectname'] if "projectname" in req else ""
    bname = req['bname'] if "bname" in req else ""
    num = req['num'] if "num" in req else ""
    sn = req['sn'] if "sn" in req else ""
    uid = req['uid'] if "uid" in req else ""
    gcname = req['gcname'] if "gcname" in req else ""
    dbtime = req['dbtime'] if "dbtime" in req else ""
    zjzb = req['zjzb'] if "zjzb" in req else ""
    special = req['special'] if "special" in req else ""
    isover = "否"

    num2 = num.replace(",", "")
    num3 = num2.replace("%", "")
    num1 = float(num3)

    if company != "":
        usercompany = company

    if num1 >= 1000000:
        isover = "是"

    index = BookIndex.query.filter_by(id=id).first()
    index.type = type
    index.company = usercompany
    index.projectname = projectname
    index.bname = bname
    index.num = num
    index.sn = sn
    index.uid = uid
    index.gcname = gcname
    index.isover = isover
    index.dbtime = dbtime
    index.zjzb = zjzb
    index.special = special
    db.session.commit()
    return ops_renderJSON(msg="更新成功")


# 详情页展示
@book_page.route('/bookdetail', methods=['GET', 'POST'])
def bookdetail():
    id = request.args.get("id")
    bookindex = BookIndex.query.filter_by(id=id).first()
    bookdetail = BookDetail.query.filter_by(pid=id, mark=1).all()
    classone = ["招标策划", "发标阶段", "谈标阶段", "定标阶段"]
    num = []
    for item in classone:
        datanum = BookDetail.query.filter_by(pid=id, classone=item, mark=1).count()
        num.append(datanum)

    alldetail = []
    for item in classone:
        bookdetail = BookDetail.query.filter_by(pid=id, classone=item, mark=1).order_by(BookDetail.classtwo).all()
        alldetail.append(bookdetail)

    return ops_render("/book/bookdetail.html",
                      {"bookdetail": bookdetail, "bookindex": bookindex, "indexid": id, "num": num,
                       "alldetail": alldetail})


# 上传文件
@book_page.route('/upload', methods=['GET', 'POST'])
def uploadfile():
    # 从前端获取文件
    f = request.files.getlist('files')
    classone = request.form.get('classone')
    # classtwo = request.form.get('classtwo')
    pid = request.form.get('pid')
    sn = request.form.get('sn')
    uid = request.form.get('uid')
    pc = request.form.get('pc')

    access_key = 'po98t2WFtFrNvPJ_bZTFobndhhKhQUk6mrXq2NX1'
    secret_key = 'DbooW85jje3wtiDP0se_JLL76PjgLGc-3p2fiEaZ'

    # 构建鉴权对象
    q = Auth(access_key, secret_key)
    # 要上传的空间
    bucket_name = 'library-filestore'
    # http://+外链域名
    domian_name = 'http://libraryfilestore.guanzhuoran.cn/'
    # 生成上传 Token，可以指定过期时间等

    for item in f:
        file = item.read()
        name = item.filename
        uploadname = sn + name
        token = q.upload_token(bucket_name, uploadname, 3600)
        ret, info = put_data(token, uploadname, data=file)
        url = domian_name + uploadname

        name, type1 = os.path.splitext(name)
        type = type1.replace(".", "")
        size = len(file) / 1000000
        size = round(size, 2)

        bookdetail = BookDetail()
        bookdetail.name = name
        bookdetail.type = type
        bookdetail.size = size
        bookdetail.url = url
        bookdetail.mark = 1
        bookdetail.uid = uid
        bookdetail.pid = pid
        bookdetail.classone = classone
        # bookdetail.classtwo = classtwo
        bookdetail.created_time = bookdetail.updated_time = getCurrentTime()
        db.session.add(bookdetail)
        db.session.commit()

    return ops_renderJSON(msg="上传成功")


@book_page.route('/detaildelete', methods=['GET', 'POST'])
def deletedetail():
    id = request.args.get('id')
    detail = BookDetail.query.filter_by(id=id).first()
    name = str(detail.name)
    type = str(detail.type)
    pid = detail.pid
    index = BookIndex.query.filter_by(id=pid).first()
    sn = index.sn
    uploadname = sn + name + "." + type

    access_key = 'po98t2WFtFrNvPJ_bZTFobndhhKhQUk6mrXq2NX1'
    secret_key = 'DbooW85jje3wtiDP0se_JLL76PjgLGc-3p2fiEaZ'
    # 初始化Auth状态
    q = Auth(access_key, secret_key)
    # 初始化BucketManager
    bucket = BucketManager(q)
    # 你要测试的空间， 并且这个key在你空间中存在
    bucket_name = 'library-filestore'
    # 删除bucket_name 中的文件 key
    ret, info = bucket.delete(bucket_name, uploadname)
    if info.status_code == 200:
        bookdetail1 = BookDetail.query.filter_by(id=id).first()
        bookdetail1.mark = 0
        db.session.commit()
        # 返回首页

        classone = ["招标阶段", "投标阶段", "谈标阶段", "定标阶段"]
        num = []
        for item in classone:
            datanum = BookDetail.query.filter_by(pid=pid, classone=item, mark=1).count()
            num.append(datanum)
        alldetail = []
        for item in classone:
            bookdetail = BookDetail.query.filter_by(pid=pid, classone=item, mark=1).all()
            alldetail.append(bookdetail)

        return ops_renderJSON(msg="删除成功", data={"pid": pid})
    if info.status_code == 612:
        return ops_renderJSON(msg="该文件已删除", data={"pid": pid})
    else:
        return ops_renderJSON(msg="删除失败")


@book_page.route('/deleteindex', methods=['GET', 'POST'])
def deleteindex():
    id = request.args.get("id")
    index = BookIndex.query.filter_by(id=id).first()
    index.mark = 0
    index.updated_time = getCurrentTime()
    db.session.add(index)
    db.session.commit()
    return ops_renderJSON(msg="删除成功")
